package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.platform.LocalContext
import com.sinogrand.elevator.ui.components.*
import com.sinogrand.elevator.repository.ProjectRepository
import com.sinogrand.elevator.data.models.ProjectItem as ApiProjectItem
import com.sinogrand.elevator.ui.components.ProjectItem as UiProjectItem
import com.sinogrand.elevator.ui.components.ProjectStatus
import com.sinogrand.elevator.utils.Constants
import com.sinogrand.elevator.utils.PaginationUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import androidx.compose.runtime.rememberCoroutineScope
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import kotlin.random.Random

@Composable
fun InstallScreen(
    paddingValues: PaddingValues = PaddingValues(),
    onNavigateToProjectDetail: (String) -> Unit = {}
) {
    val context = LocalContext.current
    val projectRepository = remember { ProjectRepository(context) }
    
    // 使用 rememberSaveable 保持所有状态，确保页面切换时状态不丢失
    var isRefreshing by rememberSaveable { mutableStateOf(false) }
    var isLoadingMore by rememberSaveable { mutableStateOf(false) }
    var projects by rememberSaveable { mutableStateOf<List<UiProjectItem>>(emptyList()) }
    var canLoadMore by rememberSaveable { mutableStateOf(true) }
    var currentPage by rememberSaveable { mutableStateOf(1) } // 当前页码
    var searchQuery by rememberSaveable { mutableStateOf("") } // 搜索关键词
    var isSearching by rememberSaveable { mutableStateOf(false) } // 搜索加载状态
    var isLoading by rememberSaveable { mutableStateOf(true) } // 初始加载状态
    val coroutineScope = rememberCoroutineScope()
    
    // 生成随机安装计划时间（YYYY-MM-DD格式）
    fun generateRandomPlannedDate(): String {
        val startDate = LocalDate.now()
        val randomDays = Random.nextLong(0, 90) // 未来90天内
        val randomDate = startDate.plusDays(randomDays)
        return randomDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
    }
    
    // 转换项目状态
    fun convertProjectStatus(status: Int): ProjectStatus {
        return when (status) {
            Constants.ProjectStatus.CONTRACT_PENDING -> ProjectStatus.PENDING
            Constants.ProjectStatus.DISABLED -> ProjectStatus.PENDING
            Constants.ProjectStatus.PROCESSING -> ProjectStatus.IN_PROGRESS
            Constants.ProjectStatus.ARCHIVE_PENDING -> ProjectStatus.APPROVED
            Constants.ProjectStatus.ARCHIVED -> ProjectStatus.COMPLETED
            else -> ProjectStatus.PENDING
        }
    }
    
    // 转换 API 项目数据为 UI 项目数据
    fun convertApiProjectToUi(apiProject: ApiProjectItem): UiProjectItem {
        val plannedDate = generateRandomPlannedDate()
        return UiProjectItem(
            id = apiProject.id.toString(),
            name = apiProject.name,
            description = "安装计划：$plannedDate | ${apiProject.address} | 电梯数量: ${apiProject.elevator_count}",
            status = convertProjectStatus(apiProject.status),
            imageUrl = null // API 返回的数据中没有图片字段
        )
    }
    
    // 加载项目列表
    fun loadProjects(page: Int = 1, searchName: String? = null, isRefresh: Boolean = false) {
        coroutineScope.launch {
            try {
                if (isRefresh) {
                    isRefreshing = true
                } else if (page == 1) {
                    isLoading = true
                } else {
                    isLoadingMore = true
                }
                
                val result = projectRepository.getInstallProjectList(
                    name = searchName,
                    page = page,
                    size = 20
                )
                
                result.fold(
                    onSuccess = { response ->
                        val uiProjects = response.list.map { convertApiProjectToUi(it) }
                        
                        if (page == 1) {
                            projects = uiProjects
                        } else {
                            projects = projects + uiProjects
                        }
                        
                        // 使用分页工具判断是否还有下一页
                        canLoadMore = PaginationUtils.hasNextPage(response.page_info)
                        currentPage = page
                    },
                    onFailure = { error ->
                        // 处理错误，可以显示错误消息
                        println("加载项目列表失败: ${error.message}")
                    }
                )
            } catch (e: Exception) {
                println("加载项目列表异常: ${e.message}")
            } finally {
                isRefreshing = false
                isLoadingMore = false
                isLoading = false
            }
        }
    }
    
    fun handleRefresh() {
        loadProjects(page = 1, searchName = if (searchQuery.isBlank()) null else searchQuery, isRefresh = true)
    }
    
    fun handleLoadMore() {
        if (!canLoadMore || isLoadingMore) return
        loadProjects(page = currentPage + 1, searchName = if (searchQuery.isBlank()) null else searchQuery)
    }
    
    fun handleProjectClick(project: UiProjectItem) {
        // 处理项目点击事件，导航到项目详情页面
        onNavigateToProjectDetail(project.id)
    }
    
    fun handleSearch(query: String) {
        searchQuery = query
        isSearching = true
        
        coroutineScope.launch {
            delay(300) // 防抖延迟
            loadProjects(
                page = 1, 
                searchName = if (query.isBlank()) null else query
            )
            isSearching = false
        }
    }
    
    // 初始加载 - 只在首次加载时执行
    LaunchedEffect(Unit) {
        // 如果项目数据为空，才进行加载
        if (projects.isEmpty()) {
            loadProjects()
        } else {
            // 如果已有数据，直接设置为非加载状态
            isLoading = false
        }
    }
    
    ProjectListScreen(
        projects = projects,
        onRefresh = { handleRefresh() },
        onLoadMore = { handleLoadMore() },
        onProjectClick = { project -> handleProjectClick(project) },
        onSearch = { query -> handleSearch(query) },
        isLoadingMore = isLoadingMore,
        canLoadMore = canLoadMore,
        isSearching = isSearching || isLoading,
        paddingValues = paddingValues
    )
}

